<template>
  <div class="selector-modal-body">
    <!-- 左侧：角色数据源（筛选+表格+分页） -->
    <div class="selector-list">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="searchParams" class="selector-search-bar" @submit.prevent>
        <el-form-item label="角色名称">
          <el-input v-model="searchParams.name" placeholder="角色名称" size="small" clearable />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchParams.code" placeholder="角色编码" size="small" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="fetchRoleList">查询</el-button>
          <el-button size="small" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格区 -->
      <div class="selector-table-wrapper">
      <el-table
          ref="tableRef"
        :data="roleList"
        style="width: 100%"
        :row-key="row => row.id"
        :highlight-current-row="!multiple"
        @row-click="onRowClick"
          @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" :selectable="() => true" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
          <el-table-column label="状态">
            <template #default="{ row }">
              <span>{{ statusMap[row.status] || '未知' }}</span>
            </template>
          </el-table-column>
      </el-table>
      </div>
      <!-- 分页区 -->
      <el-pagination
        v-if="total > 0"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        class="selector-pagination"
      />
    </div>
    <!-- 右侧：已选列表 -->
    <div class="selector-selected">
      <div class="selected-title">已选择</div>
      <el-tag
        v-for="item in selectedList"
        :key="item.id"
        closable
        @close="removeSelected(item)"
        style="margin: 4px 4px 0 0;"
      >
        {{ item.name }}
      </el-tag>
      <div v-if="!selectedList.length" class="empty-selected">暂无选择</div>
    </div>
  </div>
</template>
<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import { listRoleApi } from '@/api/system/authority/role.api'
import { nextTick } from 'vue'

// 引入统一的夜间模式样式
import '../Workflow/styles/dark-theme.css'

const props = defineProps({
  multiple: { type: Boolean, default: true },
  selectedList: { type: Array, default: () => [] },
  // 原始人员配置（用于限制模式）
  originalPersonnel: { type: Array, default: () => [] },
  // 是否限制模式
  limitedMode: { type: Boolean, default: false }
})
const emit = defineEmits(['update:selectedList', 'close'])

// 筛选参数
const searchParams = ref({
  name: '',
  code: '',
  status: ''
})
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const roleList = ref([])
const tableRef = ref()

function fetchRoleList() {
  // 重置初始化标志
  isInitializing.value = true
  
  listRoleApi({
    ...searchParams.value,
    page: pageNum.value,
    pageSize: pageSize.value
  }).then(res => {
    roleList.value = res?.items || res?.data?.rows || []
    total.value = res?.total || res?.data?.total || 0
    // 自动勾选 - 确保所有已选择的角色都被勾选
    nextTick(() => {
      if (tableRef.value) {
        console.log('RoleSelector - fetchRoleList: allSelectedRoles.value at nextTick:', allSelectedRoles.value)
        console.log('RoleSelector - fetchRoleList: roleList.value at nextTick:', roleList.value)
        
        // 先清除所有选中状态
        tableRef.value.clearSelection()
        // 然后设置已选择的行
        roleList.value.forEach(row => {
          const isSelected = allSelectedRoles.value.some(selectedRole => selectedRole.id === row.id)
          console.log(`RoleSelector - fetchRoleList: Checking row ID ${row.id} (${row.name}), isSelected: ${isSelected}`)
          if (isSelected) {
            console.log(`RoleSelector - fetchRoleList: Setting row ${row.id} (${row.name}) as selected`)
            tableRef.value.toggleRowSelection(row, true)
          }
        })
        
        // 初始化完成，允许onSelectionChange触发
        isInitializing.value = false
      }
    })
  })
}
function resetSearch() {
  searchParams.value = { name: '', code: '', status: '' }
  pageNum.value = 1
  fetchRoleList()
}
function handlePageChange(page) {
  pageNum.value = page
  fetchRoleList()
}
function handleSizeChange(size) {
  pageSize.value = size
  pageNum.value = 1
  fetchRoleList()
}

// 选中项
const selectedIds = ref([])
const allSelectedRoles = ref([]) // 存储所有已选择的角色
const isInitializing = ref(true) // 添加初始化标志
const isSyncing = ref(false) // 添加同步标志，防止在同步过程中触发onSelectionChange

watch(() => props.selectedList, (val) => {
  console.log('RoleSelector - props.selectedList changed:', val)
  console.log('RoleSelector - props.selectedList length:', val?.length)
  
  // 确保深拷贝，避免引用问题
  allSelectedRoles.value = Array.isArray(val) ? JSON.parse(JSON.stringify(val)) : []
  // 修复：selectedIds应该包含所有已选择角色的ID，而不仅仅是当前页面的
  selectedIds.value = allSelectedRoles.value.map(item => item.id)
  console.log('RoleSelector - allSelectedRoles updated:', allSelectedRoles.value)
  console.log('RoleSelector - allSelectedRoles length:', allSelectedRoles.value.length)
  
  // 同步更新表格的勾选状态
  nextTick(() => {
    if (tableRef.value && roleList.value.length > 0) {
      console.log('RoleSelector - Syncing table selection state')
      // 设置同步标志
      isSyncing.value = true
      
      // 先清除所有选中状态
      tableRef.value.clearSelection()
      // 然后设置已选择的行
      roleList.value.forEach(row => {
        const isSelected = allSelectedRoles.value.some(selectedRole => selectedRole.id === row.id)
        console.log(`RoleSelector - Syncing row ID ${row.id} (${row.name}), isSelected: ${isSelected}`)
        if (isSelected) {
          tableRef.value.toggleRowSelection(row, true)
        }
      })
      
      // 清除同步标志
      isSyncing.value = false
    } else {
      console.log('RoleSelector - Table not ready for syncing, will sync in fetchRoleList')
    }
  })
}, { immediate: true, deep: true })

const statusMap = { '0': '正常', '1': '停用' }

const selectedList = computed(() => {
  return allSelectedRoles.value
})

function onRowClick(row) {
  if (tableRef.value) {
    tableRef.value.toggleRowSelection(row)
  }
}

function onSelectionChange(selection) {
  console.log('RoleSelector - onSelectionChange called:', selection)
  console.log('RoleSelector - current allSelectedRoles before update:', allSelectedRoles.value)
  
  // 检查是否是初始化阶段或同步阶段
  if (isInitializing.value || isSyncing.value) {
    console.log('RoleSelector - onSelectionChange: Skipping update during initialization or syncing')
    return
  }
  
  // 获取当前页面中所有行的ID
  const currentPageIds = roleList.value.map(r => r.id)
  
  // 获取当前页面中选中的ID
  const currentPageSelectedIds = selection.map(s => s.id)
  
  console.log('RoleSelector - currentPageIds:', currentPageIds)
  console.log('RoleSelector - currentPageSelectedIds:', currentPageSelectedIds)
  
  // 计算当前页面中每个角色的选择状态
  const currentPageSelectionMap = {}
  currentPageIds.forEach(id => {
    currentPageSelectionMap[id] = currentPageSelectedIds.includes(id)
  })
  
  console.log('RoleSelector - currentPageSelectionMap:', currentPageSelectionMap)
  
  // 更新allSelectedRoles：保留不在当前页面的已选择角色，根据当前页面的选择状态更新
  const updatedAllSelectedRoles = [
    // 保留不在当前页面的已选择角色
    ...allSelectedRoles.value.filter(role => !currentPageIds.includes(role.id)),
    // 添加当前页面中被选中的角色
    ...roleList.value.filter(role => currentPageSelectionMap[role.id])
  ]
  
  console.log('RoleSelector - allSelectedRoles after update:', updatedAllSelectedRoles)
  
  // 更新状态
  allSelectedRoles.value = updatedAllSelectedRoles
  // 更新selectedIds为所有已选择角色的ID
  selectedIds.value = allSelectedRoles.value.map(role => role.id)
  emit('update:selectedList', allSelectedRoles.value)
}

function removeSelected(item) {
  allSelectedRoles.value = allSelectedRoles.value.filter(role => role.id !== item.id)
  
  // 更新selectedIds为所有已选择角色的ID
  selectedIds.value = allSelectedRoles.value.map(role => role.id)
  
  emit('update:selectedList', allSelectedRoles.value)
  
  // 自动取消勾选
  nextTick(() => {
    if (tableRef.value) {
      const row = roleList.value.find(r => r.id === item.id)
      if (row) tableRef.value.toggleRowSelection(row, false)
    }
  })
}

onMounted(() => {
  console.log('RoleSelector - onMounted called')
  console.log('RoleSelector - props.selectedList on mount:', props.selectedList)
  // 重置初始化标志
  isInitializing.value = true
  fetchRoleList()
})
</script>
<style scoped>
.selector-modal-body {
  display: flex;
  gap: 16px;
  min-height: 480px;
  height: 60vh;
  max-height: 80vh;
  overflow: auto;
}
.selector-list {
  flex: 2;
  background: #f7f8fa;
  border-radius: 6px;
  padding: 12px;
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.selector-search-bar {
  margin-bottom: 12px;
  flex-wrap: wrap;
}
.selector-table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: auto;
}
.selector-pagination {
  margin-top: 8px;
  text-align: right;
}
.selector-selected {
  flex: 1;
  background: #f5f7fa;
  border-radius: 6px;
  padding: 12px;
  min-width: 180px;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #e4e7ed;
}
.selected-title {
  font-weight: bold;
  margin-bottom: 8px;
}
.empty-selected {
  color: #bbb;
  margin-top: 12px;
}
</style> 